package com.ruoyi.aidesign.model;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.aidesign.config.MinioConfig;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.ByteArrayInputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * MinIO图片处理工具类
 * 用于从API返回结果中提取图片URL，下载图片并存储到MinIO
 */
public class MinioImageProcessor {

    // MinIO配置信息
    private static final String ENDPOINT = MinioConfig.getEndpoint();
    private static final String ACCESS_KEY = MinioConfig.getAccessKey();
    private static final String SECRET_KEY = MinioConfig.getSecretKey();
    private static final String BUCKET_NAME = MinioConfig.getBucketName();

    // MinIO客户端
    private static MinioClient minioClient;

    static {
        try {
            // 初始化MinIO客户端
            minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();

            // 检查并创建存储桶
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
                System.out.println("成功创建存储桶: " + BUCKET_NAME);
            }
        } catch (Exception e) {
            System.err.println("初始化MinIO客户端失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 处理API返回的JSON字符串，提取图片URL并上传到MinIO
     * @param jsonResult API返回的JSON字符串
     * @return 存储到MinIO后的新图片URL
     */
    public static String processApiResult(String jsonResult) {
        try {
            // 解析JSON
            JsonObject jsonObject = JsonParser.parseString(jsonResult).getAsJsonObject();

            // 从JSON中提取图片URL
            String imageUrl = jsonObject
                    .getAsJsonObject("output")
                    .getAsJsonArray("results")
                    .get(0)
                    .getAsJsonObject()
                    .get("url")
                    .getAsString();

            System.out.println("从API返回中提取的图片URL: " + imageUrl);

            // 下载并上传图片
            return downloadAndUploadImage(imageUrl);

        } catch (Exception e) {
            System.err.println("处理API结果失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载图片并上传到MinIO
     * @param imageUrl 图片URL
     * @return 上传到MinIO后的新URL
     */
    public static String downloadAndUploadImage(String imageUrl) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        try {
            // 下载图片
            Request request = new Request.Builder()
                    .url(imageUrl)
                    .build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful() || response.body() == null) {
                System.err.println("下载图片失败，状态码: " + response.code());
                return null;
            }

            // 获取图片数据
            byte[] imageData = response.body().bytes();
            System.out.println("图片下载成功，大小: " + imageData.length + " 字节");

            // 生成文件名
            String fileName = UUID.randomUUID().toString() + ".png";

            // 上传到MinIO
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(imageData)) {
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(BUCKET_NAME)
                                .object(fileName)
                                .stream(inputStream, imageData.length, -1)
                                .contentType("image/png")
                                .build()
                );
            }

            // 构建并返回新的URL
            String newImageUrl = ENDPOINT + "/" + BUCKET_NAME + "/" + fileName;
            System.out.println("图片已成功上传到MinIO，新URL: " + newImageUrl);

            return newImageUrl;

        } catch (Exception e) {
            System.err.println("下载或上传图片失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
